<?php


require_once("lib/exception/internal_error_exception.php");
require_once("lib/exception/instance_not_found_exception.php");

require_once("lib/model/action.php");

require_once("model/autor_message/dao/autor_message_dao_factory.php");

require_once("model/autorfacade/to/statics_autor_to.php");
require_once("model/autorfacade/to/basic_message_to.php");
require_once("model/autorfacade/to/mailbox_information_to.php");
require_once("model/autorfacade/to/all_mail_information_to.php");
require_once("model/autorfacade/to/basic_message_chunk_to.php");
require_once("model/autor_message/to/autor_message_to.php");

class Get_all_mail_send_action implements Action {

	private $login;
	private $start_index;
	private $count;
	
	public function __construct($login, $start_index, $count) {
		
		$this->login = $login;
		$this->start_index = $start_index;
		$this->count = $count;
	}
	
	public function do_execute() {
		try {
			$dao = Autor_message_dao_factory::singleton()->get_dao();
			$menssages = $dao->find_send_by_login($this->login, $this->start_index, $this->count);
			
			$more = false;
			if (count($menssages) > ($this->count+1)){
				$e = new Exception("Result list too big");
				throw new Internal_error_exception($e);
			}
			else {
				if(count($menssages) == ($this->count+1)) { 
					unset($menssages[$this->count]);
					$more = true;		
				}		
			}
			
			$message_list = NULL;
			$i = 0;
			if (!is_null($menssages)) {
				foreach ($menssages as $message) 
					$message_list[$i++] = new Basic_message_to($message->get_number(), $message->get_from_autor_login(), 
																$message->get_title(), $message->get_date(), $message->get_state());
			}
			
			$message_chunk = new Basic_message_chunk_to($message_list, $more);
			
			
			$all_inbox = $dao->count_inbox_messages_by_login($this->login);
			$new_inbox = $dao->count_new_messages_by_login($this->login);
			$send_inbox = $dao->count_send_messages_by_login($this->login);

			$mailbox_information = new Mailbox_information_to($all_inbox, $new_inbox, $send_inbox);

			return new All_mail_information_to($message_chunk, $mailbox_information);
					
		}
		catch (Instance_not_found_exception $e) {
			throw new Model_exception($e);
		}
		catch (Internal_error_exception $e) {
			throw $e;
		}
		catch (Exception $e) {
			throw new Exception("Internal error exception --> " . $e);
		}
	}
	
}
?>
